/* @(#)main.c
 * Time-stamp: <2008-10-11 19:49:04 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: main.c,v 0.0 2008/10/04 01:15:44 root Exp $
 * Keywords: 
 */

#include "common.h"

DEFINE_HASHTABLE_INSERT(insert_some, struct key, struct value);
DEFINE_HASHTABLE_SEARCH(search_some, struct key, struct value);
DEFINE_HASHTABLE_REMOVE(remove_some, struct key, struct value);
DEFINE_HASHTABLE_ITERATOR_SEARCH(search_itr_some, struct key);


int main(int argc, char *argv[]) {
	/* become deamon */
	int c, helpflg = 0;
	struct option longopts[] = {
		{"daemon", 1, 0, 'd'},
		{"help", 0, &helpflg, 'h'},
		{0,0,0,0}
	};
	while((c = getopt_long(argc, argv, "h:d", longopts, NULL)) != EOF){
		switch(c){
		case 'd':
			daemon_init("Eh0M3d", LOG_LOCAL0);
			/* daemon_init("/dev/log", LOG_DAEMON); */
			break;
		case 'h':
			helpflg = 1;
			break;
		default:
			helpflg = 0;
			break;
		}
	}
	if(helpflg){
		fprintf(stderr, "Usage: ehomed -d");
		exit(0);
	}
	
	gDispatcher = DISPATCH_DEFENSE | DISPATCH_HEART;

	err_msg("server begin...");

	if( get_db_config("/etc/ehomed.conf", &gDBConn) ) {
		err_sys("get_db_config");
	}
	
	/* err_msg("%s/%s/%s/%s\n", gDBConn.hostname,gDBConn.username,gDBConn.password,gDBConn.database); */
	
	db_init(&gDBQ, &gDBConn);
	db_init(&gDBQ_Defen, &gDBConn);  /* forr Defense() */

	db_stmt_prepare(&gDBQ);
	db_stmt_prepare(&gDBQ_Defen);

	gHash = create_hashtable(16, hash_from_key, equal_keys);
	if(NULL == gHash) err_sys("create_hashtable");

	gDevList = (devid_t*)malloc(sizeof(devid_t)* HEART_MAX);
	memset(gDevList, 0, HEART_MAX * sizeof(devid_t));

	gen_shm_device();

	/* heart thread */
	/*
	  pthread_t heart_id, defense_id;
	  int ret_thread, ret_defense;
	
	  ret_thread = pthread_create(&heart_id, NULL, (void *)Heart, NULL);
	  if(ret_thread != 0){
	  perror("Heart thread failed!\n");
	  }
	  ret_defense = pthread_create(&defense_id, NULL, (void *)Defense, NULL);
	  if(ret_defense != 0){
	  perror("Defense thread failed!\n");
	  }
	*/
	/* Signal(SIGCHLD, sig_chld); */
	/* Signal(SIGINT, exit); */
	pthread_t disp_id = 0, serv_id = 0;
	int ret;

	/* Signal(SIGALRM, sig_dispatcher); */
	
	ret = pthread_create(&disp_id, NULL, (void *)sig_engine, NULL);
	if(ret != 0){
		perror("Heart thread failed!");
	}
	ret = pthread_create(&serv_id, NULL, (void *)Server, NULL);
	if(ret != 0){
		perror("Server thread failed!");
	}

	if(disp_id) pthread_join(disp_id, NULL);
	if(serv_id) pthread_join(serv_id, NULL);	

	hashtable_destroy(gHash, 1);
	free(gDevList);

	db_stmt_release(&gDBQ);
	db_stmt_release(&gDBQ_Defen);	
	
	exit(0);
}

